// 定义棋盘组件

import "../style/board.css"
import Square from "./Square"
import { useState } from 'react'

const getNextLetter = (squares) => {
  // 找出已经被填充的棋格
  const filedSquares = squares.filter(item => item === 'X' || item === 'O')
  // 缓存长度
  const filledNumber = filedSquares.length
  // 判断当前棋格填充
  return filledNumber % 2 === 0 ? 'X' : 'O'
}
const calculateWinner = (square) => {

}
export default function Board() {
  const [squares, setSquares] = useState(new Array(9).fill(null))
  const valueMap = [0, 1, 2]
  const valueMap1 = [3, 4, 5]
  const valueMap2 = [6, 7, 8]
  const nextLetter = getNextLetter(squares)
  const winner = 'X is winner!'
  let status = null
  if (winner) {
    status = winner
  } else if (nextLetter) {
    status = `Next Player is ${nextLetter}`
  }


  const clickHandler = index => {
    if (squares[index] === 'X' || squares[index] === 'O') return
    const newSquares = [...squares]
    // const nextLetter = getNextLetter(squares)
    newSquares[index] = nextLetter
    setSquares(newSquares)
  }

  return <>
    <div className="test">{status}</div>
    <div className="board-row">
      {
        valueMap.map(v => <Square key={v} value={squares[v]} index={v} onClick={clickHandler}></Square>)
      }
    </div>
    <div className="board-row">
      {
        valueMap1.map(v => <Square key={v} value={squares[v]} index={v} onClick={clickHandler}></Square>)
      }
    </div>
    <div className="board-row">
      {
        valueMap2.map(v => <Square key={v} value={squares[v]} index={v} onClick={clickHandler}></Square>)
      }
    </div>
  </>
}
